package com.siyoumi.app.modules.sheet.web;

import com.siyoumi.app.entity.SysSheet;
import com.siyoumi.app.entity.SysSheetRecord;
import com.siyoumi.app.modules.sheet.entity.SysSheetItem;
import com.siyoumi.app.modules.sheet.service.SvcSheet;
import com.siyoumi.app.modules.sheet.vo.SysSheetSaveData;
import com.siyoumi.app.service.SysSheetRecordService;
import com.siyoumi.component.XBean;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.controller.WxAppApiController;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.util.XLog;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.map.LinkedMap;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/wxapp/sheet/z_api")
public class ApiSheet
        extends WxAppApiController {
    /**
     * 初始化
     */
    @GetMapping("init")
    public XReturn init() {
        String sheetId = input("sheet_id");
        if (XStr.isNullOrEmpty(sheetId)) {
            return EnumSys.MISS_VAL.getR("miss sheet_id");
        }
        SysSheet entitySheet = SvcSheet.getApp().getEntity(sheetId, XHttpContext.getX());
        if (entitySheet == null) {
            return EnumSys.ERR_VAL.getR("sheet_id异常");
        }

        // 子项
        List<SysSheetItem> items = SvcSheet.getBean().getItems(entitySheet.getKey());
        List<Map<String, Object>> mapItems = new ArrayList<>();
        for (SysSheetItem item : items) {
            Map<String, Object> map = XBean.toMap(item);
            mapItems.add(map);
        }

        LinkedMap<String, Object> mapSheet = new LinkedMap<>();
        mapSheet.put("sheet_id", entitySheet.getKey());
        mapSheet.put("sheet_name", entitySheet.getSheet_name());
        mapSheet.put("sheet_submit_type", entitySheet.getSheet_submit_type());
        mapSheet.put("sheet_banner_imgs", entitySheet.getSheet_banner_imgs());

        getR().setData("sheet", mapSheet);
        getR().setData("list_item", mapItems);
        getR().setData("check", SvcSheet.getBean().saveRecordCan(entitySheet.getKey()));

        return getR();
    }

    /**
     * 保存表单
     */
    @Transactional
    @PostMapping("save")
    public XReturn save(@RequestBody @Validated SysSheetSaveData vo, BindingResult result) {
        //统一验证
        XValidator.getResult(result, true, true);

        return SvcSheet.getBean().saveRecord(vo);
    }
}

